package org.aeon.fasttasks.core.recorder;

import org.aeon.fasttasks.core.util.CsvUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.system.ApplicationHome;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Date 2024/9/14 0014 9:36
 * @Author aeon
 * @Description 任务记录器
 */

public class TaskRecorder extends AbstractCsvRecorder {

    private final static Logger log = LoggerFactory.getLogger(TaskRecorder.class);

    private static final String[] HEADERS =
            {"任务序号", "任务类", "任务名称", "开始时间", "完成情况", "执行时间"};

    private final AtomicInteger taskNumber = new AtomicInteger();

    public TaskRecorder() {
        super(
                new ApplicationHome(TaskRecorder.class).getDir()
                        .toPath().resolve("TaskDetails.csv"),
                List.of(HEADERS),
                false
        );
    }

    @Override
    public synchronized void record(Object... contents) {
        try (CSVPrinter csvPrinter = CsvUtils.createCsvPrinter(path)) {
            handleHeader(csvPrinter);
            ArrayList<Object> list = new ArrayList<>(List.of(contents));
            list.add(0, taskNumber.incrementAndGet());
            csvPrinter.printRecord(list);
            csvPrinter.flush();
        } catch (IOException e) {
            log.error("记录任务清单失败");
        }
    }

    /**
     * 读取文件
     *
     * @return
     */
    public Map<String, Boolean> readTask() {
        Map<String, Boolean> taskMap = new HashMap<>();
        try (FileReader fileReader = new FileReader(path.toFile(), StandardCharsets.UTF_8)) {
            Iterable<CSVRecord> records = builderCsvFormat().parse(fileReader);

            records.forEach(record -> {
                taskMap.put(record.get(1), "正常完成".equals(record.get(4)));
                taskNumber.set(Integer.parseInt(record.get(0)));
            });
        } catch (FileNotFoundException e) {
            log.info("没有历史清单文件...");
        } catch (IOException e) {
            log.error("读取清单文件失败", e);
        }
        return taskMap;
    }


    private CSVFormat builderCsvFormat() {
        return CSVFormat.Builder.create()
                .setAllowMissingColumnNames(false)
                .setSkipHeaderRecord(true)
                // 去除数据两边的空格
                .setTrim(true)
                .setHeader(HEADERS)
                .build();
    }

}
